package com.cgt.xiaotao.product.controller;

import com.cgt.common.utils.BeanUtils;
import com.cgt.common.utils.R;
import com.cgt.xiaotao.product.domain.dto.PageDTO;
import com.cgt.xiaotao.product.domain.dto.ProductAdminDTO;
import com.cgt.xiaotao.product.domain.po.Product;
import com.cgt.xiaotao.product.domain.query.ProductPageQuery;
import com.cgt.xiaotao.product.service.IProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Api(tags = "管理端商品接口")
@Slf4j
@RestController
@RequestMapping("/admin/pro")
@RequiredArgsConstructor
public class ProductAdminController {

    private final IProductService productService;

    @ApiOperation("管理端-分页获取商品列表")
    @GetMapping("/list")
    public R<PageDTO<ProductAdminDTO>> selectAdminPage(
            @RequestParam Integer pageNo,
            @RequestParam Integer pageSize,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) boolean isAsc
    ) {
        return R.ok(productService.selectAdminPage(pageNo, pageSize, sortBy, isAsc));
    }

    @ApiOperation("管理端-获取商品详情")
    @GetMapping("/detail")
    public R<ProductAdminDTO> getProductById(@RequestParam Long id) {
        Product product = productService.getById(id);
        ProductAdminDTO productAdminDTO = BeanUtils.copyBean(product, ProductAdminDTO.class);
        return R.ok(productAdminDTO);
    }

    @ApiOperation("管理端-新增商品")
    @PostMapping("/add")
    public R<String> addProduct(@RequestBody ProductAdminDTO productAdminDTO) {
        try {
            Product product = BeanUtils.copyBean(productAdminDTO, Product.class);
            boolean result = productService.save(product);
            if (result) {
                return R.ok("新增商品成功");
            } else {
                return R.error("新增商品失败");
            }
        } catch (Exception e) {
            log.error("新增商品失败", e);
            return R.error("新增商品失败: " + e.getMessage());
        }
    }

    @ApiOperation("管理端-修改商品")
    @PostMapping("/update")
    public R<String> updateProduct(@RequestBody ProductAdminDTO productAdminDTO) {
        try {
            Product product = BeanUtils.copyBean(productAdminDTO, Product.class);
            boolean result = productService.updateById(product);
            if (result) {
                return R.ok("修改商品成功");
            } else {
                return R.error("修改商品失败");
            }
        } catch (Exception e) {
            log.error("修改商品失败", e);
            return R.error("修改商品失败: " + e.getMessage());
        }
    }

    @ApiOperation("管理端-分页条件搜索商品")
    @PostMapping("/search")
    public R<PageDTO<ProductAdminDTO>> searchProduct(@RequestBody ProductPageQuery query) {
        PageDTO<ProductAdminDTO> page = productService.searchProduct(query);
        return R.ok(page);
    }
}
